#include "serverclient.h"
#include "debug.h"

#include <unistd.h>
#include <stdio.h>
#include <cstring>

#include <string>

ServerClient::ServerClient( int fd , const struct sockaddr_in &addr ) {
	fd_ = fd ; 
	delay.lock() ;
	isConnect = true ;
	addr_ = std::move( addr ) ;
	
	taskT = new std::thread( ServerClient::task , 
							 fd_ ,
							 command_ , 
							 std::ref(isConnect) ,
							 std::ref(delay) ) ;
}

ServerClient::~ServerClient() {
	isConnect = false ;
	delay.unlock() ;
	taskT->join() ;
}


void ServerClient::runCommand( const char *command ) {
	strcpy( command_ , command ) ;
	delay.unlock() ;
}

int ServerClient::getFd() {
	return fd_ ;
}

struct sockaddr_in ServerClient::getDetail() {
	return addr_ ;
}

void ServerClient::task( int socfd , 
						 char *command , 
						 bool &isConnect , 
						 std::mutex &delay  ) { 
	while ( true ) {
		delay.lock() ;
		if ( !isConnect ) return ;
		FILE *fp =  popen( command , "r" ) ;
		if ( fp == NULL ) debug() << "popen() return NULL\n" ;
		std::string allRead ; 
		while ( !feof( fp ) ) {
			int count = fread( command , 1 , BUFSIZ , fp ) ;
			command[count] = 0 ;
			allRead += std::string(command) ;
		}
		write( socfd , allRead.data() , allRead.size() ) ;
		pclose(fp) ;
	}
}






